package com.snail.starter.mq.holder;

import com.snail.starter.utils.spring.SpringBeanContext;
import com.snail.starter.commons.exception.BizException;
import com.snail.starter.mq.dto.LocalMessageDTO;
import com.snail.starter.mq.enums.LocalMessageTypeEnum;
import com.snail.starter.mq.enums.MQStarterErrorCode;
import com.snail.starter.mq.producer.IMessageProducer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author: snail framework
 * @Date: 2023/7/4 15:18
 * @Version: 1.0.0
 */
@Slf4j
@Component
public class MessageHolder {

    public boolean sendByLocalMessage(LocalMessageDTO localMessageDTO) {
        return iMessageProducer(localMessageDTO).sendByLocalMessage(localMessageDTO);
    }

    public boolean send(LocalMessageDTO localMessageDTO) {
        return iMessageProducer(localMessageDTO).send(localMessageDTO);
    }

    private IMessageProducer iMessageProducer(LocalMessageDTO localMessageDTO) {
        List<IMessageProducer> iMessageProducers = SpringBeanContext.getBeanList(IMessageProducer.class);
        if (null == iMessageProducers || iMessageProducers.isEmpty()) {
            log.error("MessageHolder#sendByLocalMessage miss, localMessageDTO:{}", localMessageDTO);
            throw BizException.of(MQStarterErrorCode.MISS_MESSAGE_PRODUCER);
        }
        IMessageProducer messageProducer = iMessageProducers.stream()
                .filter(iMessageProducer -> iMessageProducer.supportMessageType(LocalMessageTypeEnum.getEnumByType(localMessageDTO.getMessageType())))
                .findFirst().orElse(null);
        if (null == messageProducer) {
            log.error("MessageHolder#sendByLocalMessage not match, localMessageDTO:{}", localMessageDTO);
            throw BizException.of(MQStarterErrorCode.NOT_MATCH_MESSAGE_PRODUCER);
        }
        return messageProducer;
    }

}